package servlet.admin;

import entity.Blog;
import service.BlogService;
import service.Impl.BlogServiceImpl;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

@WebServlet("/admin/BlogFindByTime")
public class BlogFindByTimeServlet extends HttpServlet {
    private BlogService blogService = new BlogServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String blogTimeStr = req.getParameter("actionTime");
        if (blogTimeStr == null || blogTimeStr.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少活动时间参数");
            return;
        }

        try {
            LocalDate blogTime = LocalDate.parse(blogTimeStr);
            List<Blog> blogList = blogService.findByTime(String.valueOf(blogTime));
           // System.out.println(blogList);

            JSONObject jsonResponse = new JSONObject();
            JSONArray jsonArray = new JSONArray();

            for (Blog blog : blogList) {
                JSONObject jsonBlog = new JSONObject();
                jsonBlog.put("id", blog.getId());
                jsonBlog.put("title", blog.getTitle());
                jsonBlog.put("actionTime", blog.getActionTime());
                jsonBlog.put("address", blog.getAddress());
                jsonBlog.put("peoples", blog.getPeoples());
                jsonBlog.put("event", blog.getEvent());
                jsonArray.put(jsonBlog);
            }

            jsonResponse.put("success", true);
            jsonResponse.put("blogList", jsonArray);

            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(jsonResponse.toString());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("success", false);
            errorResponse.put("error", "无效的日期格式");
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(errorResponse.toString());
        }
    }
}